<?php

namespace App\Http\Controllers\admin;

use App\Common\Responses;
use App\Http\Controllers\Controller;
use App\Models\Estate;
use App\Utils\Lib\MyEs;
use App\Utils\Logic\lak\EsSearchLogic;
use App\Utils\Logic\lak\RedisRankHistoryLogic;
use Illuminate\Http\Request;
class TestController extends Controller
{
    /*
     * 创建索引
     * @name lak
     * */
    public function CreateIndex(){
        try {
            $index='text_lak';
            $res= (new MyEs())->create_index($index);
            return Responses::success($res,200,'索引创建成功');
        }catch (\Exception $exception){
            return Responses::error([],2001,'失败');
        }
    }




      /*
       * es搜索
       * @name lak
       * */
    public function search(Request $request)
    {
        try {
            $name = $request->get('house');
            $page = $request->get('page')?:1;
            $size = $request->get('size')?:10;
            $from = ($page-1)*$size;
            //es搜索
            if (!empty($name)) {

                RedisRankHistoryLogic::RedisRankHistory($name);

                $data = EsSearchLogic::EsSearch($name,'location',$from,$size);

                //实现Es高亮分页检索
                $data =  json_decode(json_encode($data),true);
                return Responses::success($data,200,'成功');
            }
            $data = Estate::paginate(10);
            $data =  json_decode(json_encode($data),true);
            return Responses::success($data,200,'添加成功');
        }catch (\Exception $exception){
            return Responses::error([],2001,'失败');
        }

    }

    /*
     * 搜索历史记录
     * lak
     * */
    public function EsHistory(){
        try {
            $redis = \App\Utils\Lib\Redis::createRedisObject();
            $redis->select(10);
            $key = 'es_history';
            $data = $redis->lRange($key,0,-1);
            return Responses::success($data,200,'添加成功');
        }catch (\Exception $exception){
            return Responses::error([],2001,'失败');
        }
    }


    /*
     * 搜索排行榜 从高到低
     * lak
     * */
    public function EsRank(){
        try {
            $redis = \App\Utils\Lib\Redis::createRedisObject();
            $redis->select(11);
            $k = 'es_rank';
            // 获取搜索热搜排行榜
            $data = $redis->zRevRange($k, 0, 9, true);
            return Responses::success($data,200,'添加成功');
        }catch (\Exception $exception){
            return Responses::error([],2001,'失败');
        }
    }

    /*
     * 搜索排行榜 从低到高
     * lak
     * */
    public function EsRankZrange(){
        try {
            $redis = \App\Utils\Lib\Redis::createRedisObject();
            $redis->select(11);
            $k = 'es_rank';
            // 获取搜索热搜排行榜
            $data = $redis->ZRANGE($k, 0, 9, true);
            return Responses::success($data,200,'添加成功');
        }catch (\Exception $exception){
            return Responses::error([],2001,'失败');
        }
    }













}
